﻿/****************
* Authored by Zhuo "Wizcas" Chen
* 2018 © Wubi.fun all rights reserved
*****************/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MergeRequest : MonoBehaviour 
{
    public Vector3 offset = Vector3.up * .5f;
    [SerializeField] ParticleSystem _fxPrefab;
    [SerializeField] TextMesh _text;
    [SerializeField] SpriteRenderer _icon;

    public AudioClip canMergeSfx;
    public AudioClip mergeSuccSfx;
    public AudioClip mergeFailSfx;

    BlockStack _stk;
    BlockStack stack { get { return _stk ?? (_stk = GetComponentInParent<BlockStack>()); } }

    private void Awake()
    {
        ToggleTips(false);
        gameObject.SetActive(false);
    }

    private void Update()
    {
        transform.position = offset + stack.topPos;
        transform.rotation = Camera.main.transform.rotation;
    }

    private void OnMouseEnter()
    {
        ToggleTips(true);
    }

    private void OnMouseExit()
    {
        ToggleTips(false);
    }

    private void OnMouseUpAsButton()
    {
        var succ = stack.Merge();
        if (succ)
        {
            Instantiate(_fxPrefab, transform.position, Quaternion.identity);
        }
        stack.audioSrc.PlayOneShot(succ ? mergeSuccSfx : mergeFailSfx);
    }

    public void SetVisible(bool isVisible, Res price)
    {
        if (!gameObject.activeSelf && isVisible)
        {
            stack.audioSrc.PlayOneShot(canMergeSfx);
        }
        if (gameObject.activeSelf != isVisible)
        {
            gameObject.SetActive(isVisible);
        }
        if (isVisible)
        {
            Update();
            _text.text = string.Format("Pay    x{0}", Mathf.Abs(price.amount));
            _icon.sprite = price.icon;
        }
    }

    void ToggleTips(bool isOn)
    {
        _text.gameObject.SetActive(isOn);
        _icon.gameObject.SetActive(isOn);
    }
}
